package com.atguigu.survey.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DataProcessUtils {

    /**
     * 
     * @方法名: md5
     * @功能描述: 采用MD5进行加密
     * @param source 要加密的字符串
     * @return 加密后的字符串，如果无法加密，返回null
     * @作者 HW
     * @日期 2018年3月13日
     */
    public static String md5(String source) {
        // 判断需要加密的字符串是否为空
        if (source == null || source.length() == 0) {
            return null;
        }
        // 将需要加密的字符串转换为字节数组
        byte[] bytes = source.getBytes();

        // 将需要加密的字符串的字节数组进行加密
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] digestBytes = messageDigest.digest(bytes);
            return convertToString(digestBytes);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;

    }

    private static String convertToString(byte[] digestBytes) {
        
        StringBuilder builder = new StringBuilder();
        int length = digestBytes.length;
        char [] codeArr = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        for (int i = 0; i < digestBytes.length; i++) { 
            
            byte codeByte = digestBytes[i];
            
            int lowCode = codeByte & 15 ; //低四位
            int hightCode = ( codeByte >> 4 ) & 15 ; //高四位
            
            //以高四位和低四位从字符池中来获取字符
            char lowChar = codeArr[lowCode];
            char hightChar = codeArr[hightCode];
            
            //将32字符拼串
            builder.append(hightChar).append(lowChar);
    }
    
    return builder.toString();
    }
}
